package base.stream;

import java.io.*;

// 字节缓冲流
// BufferedInputStream
// BufferedOutputStream
public class BufferedInputandOutputStreamDemo {
    public static void main(String[] args) throws FileNotFoundException {

        // 1. 创建源
        // 2. 选择流
        // 3. 操作(分段读取)
        // 4. 释放资源

        // bufferrdInputStream demo
        inputStream();

        // bufferedOutput Stream demo
//        outpuStream();

    }

    public static void inputStream() throws FileNotFoundException {

        try (
                BufferedInputStream bufferedInput = new BufferedInputStream(
                             new FileInputStream("C:\\Temp\\test\\test.txt")
                        // 指定缓冲区大小
                        , 2)
        ) {
            // 自定义缓冲区
            byte[] bufferContainer = new byte[6];

            bufferedInput.read(bufferContainer);
            int readLength = -1;

            String str = new String(bufferContainer);

            while ((readLength = bufferedInput.read()) != -1) {
                // 分配一个新String字符，其中包含来自character array参数的子数组的字符。
                System.out.print((char) readLength);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public static void outpuStream() {
        try (
                //  Creates a new buffered output stream to write data to the
                //  specified underlying output stream.
                BufferedOutputStream output = new BufferedOutputStream(
                        // name        the system-dependent file name
                        // append       if <code>true</code>,
                        //              then bytes will be written to the end of the file rather than the beginning
                        new FileOutputStream("C:\\Temp\\test\\test.txt ", true)
                        //  size   the buffer size 缓冲区大小
                        , 1024
                )
        ) {
            String msg = "BufferedOutputStream";

            output.write(msg.getBytes());

            // Flushes this buffered output stream.
            // This forces any buffered output bytes to be written out to the underlying output stream.
            // 刷新缓冲输出流(刷新缓冲区), 这就迫使任何缓冲输出字节写入底层输出流。
            output.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
